package top.zkh.login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.java1234.dao.UserDao;
import com.java1234.model.User;
import com.java1234.util.DbUtil;
import com.java1234.util.StringUtil;

public class UserServlet extends HttpServlet {

	private DbUtil dbUtil = new DbUtil();
	private UserDao userDao = new UserDao();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		Connection con =null;
		PreparedStatement ps =null;
		Map<String,String[]> map =req.getParameterMap();
		String username = req.getParameter("userName");
		String password = req.getParameter("password");
		if(StringUtil.isEmpty(username)) {
			req.getRequestDispatcher("erroruser.jsp").forward(req, resp);
			return;
		}
		if(StringUtil.isEmpty(password)) {
			req.getRequestDispatcher("erroruser.jsp").forward(req, resp);
			return;
		}
		User user = new User(username,password);
		try {
			con = dbUtil.getCon();
			User currentUser=userDao.login(con, user);
			if(currentUser !=null) {
				HttpSession session = req.getSession();
				session.setAttribute("username", user.getUserName());
				req.getRequestDispatcher("userfind.jsp").forward(req, resp);
				}else {
				req.getRequestDispatcher("erroruser.jsp").forward(req, resp);
				}
			} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}finally {
				try {
				dbUtil.closeCon(con);
				} catch (Exception e) {
				// TODO Auto-generated catch block
					e.printStackTrace();
					}
				}
		}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

}
